
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "hex.h"
#define SOFTWARE_NAME 	"udp"
int main(int argc, char **argv)
{
  //char *ip = "0.0.0.0";
  char *ip = "192.168.1.131";
  int fd, port = 56100;

  fd = socket(AF_INET, SOCK_DGRAM, 0);
  if (fd < 0) {
    perror("Socket creation failed");
    exit(1);
  }

  struct sockaddr_in server_addr;
  socklen_t addrlen = sizeof(server_addr);
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(port);
  server_addr.sin_addr.s_addr = inet_addr(ip);
  uint8_t message[4] = {0x31, 0x32, 0x33, 0x34};
  size_t size = 4;//strlen(message);
  printf("sendto: %ld\n", size);
  hex_print(message, size);
  //exit(1);
  if (sendto(fd, message, size, 0,
        (struct sockaddr *)&server_addr, addrlen) < 0) {
    perror("Send failed");
    goto err;
  }
  uint8_t buffer[1024];
  int n = recv(fd, buffer, sizeof(buffer) - 1, 0);
  if (n < 0) {
    perror("Receive failed");
    exit(1);
  }
  //buffer[n] = '\0';  // 确保字符串结束
  printf("Received from server: %d\n", n);
  hex_print(buffer, n);
  printf("sendto ip:%d.%d.%d.%d:%d\n",
      buffer[31], buffer[32], buffer[33], buffer[34],
      *(uint32_t *)(buffer + 35));
  //printf("Received from server: %s\n", buffer);
err:
  close(fd);
#ifdef USE_GLIB
  gpointer res;//, address;
  GObject *udp;
  gchar *ip = "0.0.0.0";
  gint rc = 0, port = 80;

  if (argc > 1)
    port = atoi(argv[1]);

  GInetAddress *addr = NULL;
  GSocketAddress *saddr = NULL;

  addr = g_inet_address_new_from_string(ip);
  saddr = g_inet_socket_address_new(addr, port);
  udp = udp_open(NULL, 0);
  while (1) {
    sleep(2);
    res = udp_send(udp, saddr, "ldfsf", 5);
    if (res) {
    }
  }
	return rc;
#endif
}
